package com.love.cloud.common.dubbo.filter;
import com.love.cloud.common.core.constant.DubboConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 消费者过滤器
 * @author hongdongqu
 */
@Slf4j
@Activate(group = CommonConstants.CONSUMER)
public class DubboConsumerFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        if (invoker.getUrl() == null) {
            log.error("调用Dubbo服务时，准备动作处理失败！");
            throw new RpcException("调用Dubbo服务时，准备动作处理失败！");
        }
        RpcContext context = RpcContext.getContext();
        this.setTokenInfo(context);
//        RpcContext.getContext()
//                .setInvoker(invoker)
//                .setInvocation(invocation)
//                .setLocalAddress(NetUtils.getLocalHost(), 0)
//                .setRemoteAddress(invoker.getUrl().getHost(),
//                        invoker.getUrl().getPort());
//        if (invocation instanceof RpcInvocation) {
//            ((RpcInvocation)invocation).setInvoker(invoker);
//        }
        return invoker.invoke(invocation);

//            log.error("调用Dubbo服务时失败！Path：".concat(currentPath));
//
//            CompletableFuture b = new CompletableFuture ();
//            AsyncRpcResult asyncRpcResult = new AsyncRpcResult(b,invocation);
//            asyncRpcResult.setValue("Consumer 服务失败，Dubbo Consumer 停止调用！Path：" + currentPath);
//            return asyncRpcResult;
    }

    private void setTokenInfo(RpcContext context){
        //优先从rpc上下文中获取
        String token = RpcContext.getContext().getAttachment(DubboConstant.ACCESS_TOKEN_KEY);
        if (StringUtils.isEmpty(token)) {
            //从http请求头里面获取到token信息
            RequestAttributes ra = RequestContextHolder.getRequestAttributes();
            if(!Objects.isNull(ra)){
                ServletRequestAttributes sra = (ServletRequestAttributes) ra;
                HttpServletRequest request = sra.getRequest();
                String tokenInfo = request.getHeader("Authorization");
                if (StringUtils.isNotEmpty(tokenInfo)) {
                    context.setAttachment(DubboConstant.ACCESS_TOKEN_KEY,tokenInfo.replace("Bearer ",""));
                }
            }
        }
    }
}
